package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.BigUnitBean;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.Bean.UpgradeBean;
import com.zhongkai.CryptoUtil;
import com.zhongkai.MessageTool;
import com.zhongkai.StringStatic;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.app.service.SetUnitService;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.listener.RocketMqProducer;
import com.zhongkai.model.utils.TTHelp;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 设备列表
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SetUnitServiceImpl implements SetUnitService {

    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private PageQuerDao pageQuerDao;
    @Autowired
    private RocketMqProducer rocketMqProducer;



/*    @Autowired
    private JmsTemplate jmsTemplate;


    @Resource
    private Destination topicDestination;*/

/*    @Autowired
    private RedisUtils redisUtils;*/

    @Autowired
    private JedisClient jedisClient;


    /**
     * 查询 在线 离线
     *
     * @param trus 标识 1未绑定 2已托管  3已绑定
     * @param wire 是否在线 1在线 2离线 3开机 4关机
     */

    @Override
    public ZhongkaiResult unit_search(String trus, String wire, Integer page, Integer rows) {
        if (StringUtils.isNullOrEmpty(trus) || StringUtils.isNullOrEmpty(wire) || page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
            detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件

            if ("2".equals(wire)) {
                detachedCriteria.add(Restrictions.eq("setStatus", 100)); // 是否在线
            } else if ("1".equals(wire)) {
                detachedCriteria.add(Restrictions.ne("setStatus", 100)); // ne 代表不等于
            } else if ("4".equals(wire)) {
                detachedCriteria.add(Restrictions.eq("setStatus", 0)); // 是否在线
            } else if ("3".equals(wire)) {
                Collection collection = new ArrayList();

                ((ArrayList) collection).add(1);
                ((ArrayList) collection).add(2);
                ((ArrayList) collection).add(3);
                ((ArrayList) collection).add(4);
                ((ArrayList) collection).add(5);
                ((ArrayList) collection).add(6);
                detachedCriteria.add(Restrictions.in("setStatus", collection)); //增加条件 1-6 启动中的设备
            }

            if ("1".equals(trus)) {
                detachedCriteria.add(Restrictions.eq("setBound", "1")); //增加条件 是否绑定业主1 不是

            } else if ("3".equals(trus)) {
                detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主2是
            } else if ("2".equals(trus)) {
                detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主 1未绑定 2已绑定
                detachedCriteria.add(Restrictions.eq("trusteeship", "2")); //增加条件 是否托管 1未托管 2已托管
            }


            //detachedCriteria.addOrder(Order.desc("setStatus"));//根据传入的字段进行降序排序
            //  detachedCriteria.addOrder(Order.asc("setStatus"));//Order.asc --> 根据传入的字段进行升序排序 1 开机 2 关机 3离线
            pageBean.setDetachedCriteria(detachedCriteria);

            pageQuerDao.pageQuery(pageBean);

            List<SetUnit> rows1 = pageBean.getRows(); //取出数据

            BigUnitBean bigUnitBean_json; //实时数据

            ObjectMapper mapper = new ObjectMapper(); //解析json类

            String uuid;

            for (SetUnit setUnit : rows1) {

                uuid = setUnit.getSetUuid();
                String json = (String) jedisClient.get(StringStatic.REDIS_UNIT + uuid); //查询缓存

                if (!StringUtils.isNullOrEmpty(json)) {
                    bigUnitBean_json = mapper.readValue(json, BigUnitBean.class);

                    //  setUnit.setSetStatus(Integer.valueOf(bigUnitBean_json.getState()));//设备状态

                    setUnit.setEnergy(Integer.valueOf(bigUnitBean_json.getUser_t())); //设备设定温度

                    setUnit.setBattery(Long.valueOf(bigUnitBean_json.getPower_all())); //总耗电量

                }
/*
                else {

                    //   deviceOperationService.deviceDown2(uuid);
                    setUnit.setSetStatus(100);
                }*/
            }

            pageBean.setRows(rows1); //设置回去
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }

    /**
     * 设备列表
     *
     * @param is_assign 是否绑定业主 1否 2是
     * @param page      当前页数
     * @param rows      每页数据条数
     */
    @Override
    public ZhongkaiResult unit_list(String is_assign, Integer page, Integer rows) {

        if (StringUtils.isNullOrEmpty(is_assign)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        try {
            DecimalFormat df=new DecimalFormat("0.00");//设置保留位数
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
            detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件
            detachedCriteria.add(Restrictions.eq("setBound", is_assign)); //增加条件 是否绑定业主
            //detachedCriteria.addOrder(Order.desc("setStatus"));//根据传入的字段进行降序排序
            detachedCriteria.addOrder(Order.asc("setStatus"));//Order.asc --> 根据传入的字段进行升序排序 1 开机 2 关机 3离线
            pageBean.setDetachedCriteria(detachedCriteria);

            pageQuerDao.pageQuery(pageBean);

            List<SetUnit> rows1 = pageBean.getRows(); //取出数据

            BigUnitBean bigUnitBean_json; //实时数据

            ObjectMapper mapper = new ObjectMapper(); //解析json类

            String uuid;

            for (SetUnit setUnit : rows1) {

                uuid = setUnit.getSetUuid();
                String json = (String) jedisClient.get(StringStatic.REDIS_UNIT + uuid); //查询缓存

                if (!StringUtils.isNullOrEmpty(json)) {
                    bigUnitBean_json = mapper.readValue(json, BigUnitBean.class);

                    // setUnit.setSetStatus(Integer.valueOf(bigUnitBean_json.getState()));//设备状态

                    setUnit.setEnergy(Integer.valueOf(bigUnitBean_json.getUser_t())); //设备设定温度

                    setUnit.setBattery(Long.valueOf(bigUnitBean_json.getPower_all())/10); //总耗电量

                }

/*                else {

                    //   deviceOperationService.deviceDown2(uuid);
                    // setUnit.setSetStatus(100);
                }*/
            }

            pageBean.setRows(rows1); //设置回去
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }

    }


    /**
     * 修改已绑定用户设备信息
     *
     * @param uuid         设备uuid
     * @param address      详细地址
     * @param province     省
     * @param city         市
     * @param country      区
     * @param town         乡镇
     * @param longitude    经度
     * @param latitude     纬度
     * @param set_vol_uuid 大客户uuid 传0代表没有
     * @param set_alias    设备别名
     */
    @Override
    public ZhongkaiResult unit_update(String uuid, String address, String province, String city,
                                      String country, String town,
                                      String longitude, String latitude,
                                      String set_vol_uuid, String set_alias
    ) {
        if (StringUtils.isNullOrEmpty(uuid) || StringUtils.isNullOrEmpty(address)
                || StringUtils.isNullOrEmpty(province) || StringUtils.isNullOrEmpty(city) || StringUtils.isNullOrEmpty(country)
                || StringUtils.isNullOrEmpty(longitude) || StringUtils.isNullOrEmpty(latitude)
                || StringUtils.isNullOrEmpty(set_vol_uuid) || StringUtils.isNullOrEmpty(set_alias)

                ) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + uuid + "'");

        if (setUnit == null) {
            return ZhongkaiResult.build(400, "此设备不存在");
        } else if ("1".equals(setUnit.getSetBound())) {
            return ZhongkaiResult.build(400, "此设备还未绑定户主");
        }


        Province province1 = (Province) iBaseDao.get("from Province pr where pr.provinceId='" + province + "'");

        City city1 = (City) iBaseDao.get("from City pr where pr.cityId='" + city + "'");

        Country country1 = (Country) iBaseDao.get("from Country pr where pr.countryId='" + country + "'");

        if (province1 == null || city1 == null || country1 == null) {
            return ZhongkaiResult.build(500, "该地区不存在,请重新选择");
        }
        String address_all = "";

        if ("1".equals(town) || StringUtils.isNullOrEmpty(town)) {
            address_all = province1.getName() + city1.getName() + country1.getName() + address;

        } else {
            Town town1 = (Town) iBaseDao.get("from Town pr where pr.townId='" + town + "'");
            address_all = province1.getName() + city1.getName() + country1.getName() + town1.getName() + address;
        }

        if ("0".equals(set_vol_uuid)) {
            setUnit.setSetVolName("无");
            setUnit.setSetVolUuid("无");
        } else {
            Chinaset chinaset = (Chinaset) iBaseDao.get("from Chinaset se where se.uuid='" + set_vol_uuid + "'");
            if (chinaset == null) {
                return ZhongkaiResult.build(500, "该大客户不存在");
            } else {
                setUnit.setSetVolName(chinaset.getSetName());
                setUnit.setSetVolUuid(set_vol_uuid);
            }
        }


        setUnit.setAppAddress(address);
        setUnit.setAppProvince(province);
        setUnit.setAppCity(city);
        setUnit.setAppCountry(country);
        setUnit.setAppTown(town);
        setUnit.setLongitude(longitude);
        setUnit.setLatitude(latitude);
        setUnit.setAppAddressAll(address_all);

        setUnit.setSetAlias(set_alias); //设备别名

        //FsonUser

        iBaseDao.update1("update FsonUser unit set unit.setAlias='" + set_alias + "' where unit.fUid='" + uuid + "'");

        //System.out.println("执行了");
        //List<FsonUser> list = iBaseDao.find("from FsonUser su where su.fUid='"+uuid+"'");

        //   System.out.println(String.valueOf(list.size()));
/*        if (list != null){
            for (FsonUser fsonUser : list) {
                fsonUser.setSetAlias(setUnit.getSetAlias());

                iBaseDao.update(fsonUser);
            }
        }*/
        try {

            iBaseDao.update(setUnit);
            return ZhongkaiResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "修改失败,请联系管理员");
        }

    }


    /**
     * 删除设备
     *
     * @param uuid 设备uuid
     */
    @Override
    public ZhongkaiResult unit_remove(String uuid) {
        if (StringUtils.isNullOrEmpty(uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + uuid + "'");

        if (setUnit == null) {
            return ZhongkaiResult.build(400, "此设备不存在");
        }

        List<FsonUser> fsonUsers = iBaseDao.find("from FsonUser su where su.fUid='" + uuid + "'");

        if (fsonUsers != null) {
            if (fsonUsers.size() != 0) {
                for (FsonUser fsonUser : fsonUsers) {

                    iBaseDao.delete(fsonUser);
                }
            }
        }


        iBaseDao.delete(setUnit);
        return ZhongkaiResult.ok();

    }


    /**
     * 设备搜索
     *
     * @param name     设备绑定的用户  非必填
     * @param province 省            非必填
     * @param city     市            非必填
     * @param country  区            非必填
     * @param town     乡镇          非必填
     * @param page     当前页数
     * @param rows     每页数据条数
     */
    @Override
    public ZhongkaiResult unit_userQ(String name, String province, String city, String country, String town, Integer page, Integer rows) {
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "参数不完整");
        }

        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
            detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件
            detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主 2已绑定  1 未绑定

            if (!StringUtils.isNullOrEmpty(name)) {
                detachedCriteria.add(Restrictions.like("userName", name, MatchMode.ANYWHERE)); //字符串在中间匹配.相当于"like '%value%'"
            }


            if (!StringUtils.isNullOrEmpty(province)) {
                detachedCriteria.add(Restrictions.eq("appProvince", province)); //增加条件
            }

            if (!StringUtils.isNullOrEmpty(city)) {
                detachedCriteria.add(Restrictions.eq("appCity", city)); //增加条件
            }

            if (!StringUtils.isNullOrEmpty(town)) {
                detachedCriteria.add(Restrictions.eq("appTown", town)); //增加条件
            }

            if (!StringUtils.isNullOrEmpty(country)) {
                detachedCriteria.add(Restrictions.eq("appCountry", country)); //增加条件
            }


            //detachedCriteria.addOrder(Order.desc("setStatus"));//根据传入的字段进行降序排序
            //  detachedCriteria.addOrder(Order.asc("setStatus"));//Order.asc --> 根据传入的字段进行升序排序

            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean); //查询


            List<SetUnit> rows1 = pageBean.getRows(); //取出数据

            BigUnitBean bigUnitBean_json; //实时数据

            ObjectMapper mapper = new ObjectMapper(); //解析json类

            String uuid;

            for (SetUnit setUnit : rows1) {

                uuid = setUnit.getSetUuid();
                String json = (String) jedisClient.get(StringStatic.REDIS_UNIT + uuid); //查询缓存

                if (!StringUtils.isNullOrEmpty(json)) {
                    bigUnitBean_json = mapper.readValue(json, BigUnitBean.class);

                    //   setUnit.setSetStatus(Integer.valueOf(bigUnitBean_json.getState()));//设备状态

                    setUnit.setEnergy(Integer.valueOf(bigUnitBean_json.getUser_t())); //设备设定温度

                    setUnit.setBattery(Long.valueOf(bigUnitBean_json.getPower_all())); //总耗电量

                }
            }

            pageBean.setRows(rows1); //设置回去


            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }


    /**
     * 已托管设备列表
     *
     * @param page 当前页数
     * @param rows 每页数据条数
     */
    @Override
    public ZhongkaiResult unit_trusteeship(Integer page, Integer rows) throws IOException {
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "参数不完整");
        }


        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SetUnit.class);
        detachedCriteria.add(Restrictions.eq("setRemove", "1")); //增加条件
        detachedCriteria.add(Restrictions.eq("setBound", "2")); //增加条件 是否绑定业主 1未绑定 2已绑定
        detachedCriteria.add(Restrictions.eq("trusteeship", "2")); //增加条件 是否托管 1未托管 2已托管
        //detachedCriteria.addOrder(Order.desc("setStatus"));//根据传入的字段进行降序排序
        //  detachedCriteria.addOrder(Order.asc("setStatus"));//Order.asc --> 根据传入的字段进行升序排序

        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);

        List<SetUnit> rows1 = pageBean.getRows(); //取出数据

        BigUnitBean bigUnitBean_json; //实时数据

        ObjectMapper mapper = new ObjectMapper(); //解析json类

        String uuid;

        for (SetUnit setUnit : rows1) {

            uuid = setUnit.getSetUuid();
            String json = null; //查询缓存
            try {
                json = (String) jedisClient.get(StringStatic.REDIS_UNIT + uuid);
            } catch (Exception e) {
                e.printStackTrace();
                return ZhongkaiResult.build(500, "redis连接获取失败");
            }

            if (!StringUtils.isNullOrEmpty(json)) {
                bigUnitBean_json = mapper.readValue(json, BigUnitBean.class);

                //        setUnit.setSetStatus(Integer.valueOf(bigUnitBean_json.getState()));//设备状态

                setUnit.setEnergy(Integer.valueOf(bigUnitBean_json.getUser_t())); //设备设定温度

                setUnit.setBattery(Long.valueOf(bigUnitBean_json.getPower_all())); //总耗电量

            }
        }

        pageBean.setRows(rows1); //设置回去


        return ZhongkaiResult.ok(pageBean);

    }


    /**
     * 已托管设备列表
     *
     * @param list 当前需要升级的设备集合
     */
    @Override
    public ZhongkaiResult unit_upgrade(final String list) {

        if (list == null) {
            return ZhongkaiResult.build(500, "参数不完整");
        }


        // System.out.println(list);

        //      textMessage = session.createTextMessage("UpgradeBean:" + list);

        try {
            byte[] bytes = list.getBytes("utf-8");
            rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY, MessageTool.UNIT_UPDE, bytes);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

/*        jmsTemplate.send(topicDestination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {



                return textMessage;
            }
        });*/
        return ZhongkaiResult.ok();
    }


    /**
     * 区域升级
     *
     * @param area   区域标识 1省 2市 3区 4乡镇
     * @param areaId 区域id
     */

    @Override
    public ZhongkaiResult unit_area(String area, String areaId) {
        final List<Object[]> list;

        if (StringUtils.isNullOrEmpty(area) || StringUtils.isNullOrEmpty(areaId)) {

            return ZhongkaiResult.build(500, "数据不完整");
        }
        switch (area) {
            case "1":
                list = iBaseDao.find("select setUuid,setIp from SetUnit se where se.appProvince='" + areaId + "'");
                break;
            case "2":
                list = iBaseDao.find("select setUuid,setIp from SetUnit se where se.appCity='" + areaId + "'");
                break;
            case "3":

                list = iBaseDao.find("select setUuid,setIp from SetUnit se where se.appCountry='" + areaId + "'");
                break;

            case "4":
                list = iBaseDao.find("select setUuid,setIp from SetUnit se where se.appTown='" + areaId + "'");
                break;
            default:
                return ZhongkaiResult.build(500, "参数不合法");
        }

        // UpgradeBean
        final List<UpgradeBean> upgradeBeans = new ArrayList<>();


        for (Object[] objects : list) {
            UpgradeBean bean = new UpgradeBean();
            bean.setUnitUuid(objects[0].toString());
            bean.setUnitIp(objects[1].toString());
            upgradeBeans.add(bean);
            bean = null;
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            //  textMessage = session.createTextMessage("UpgradeBean:" + );
            String json = mapper.writeValueAsString(upgradeBeans);

            byte[] bytes = json.getBytes("utf-8");
            rocketMqProducer.sendMsgIntime(MessageTool.BIG_SKY, MessageTool.UNIT_UPDE, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }

/*        jmsTemplate.send(topicDestination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {


                return textMessage;
            }
        });*/
        //  System.out.println(new Gson().toJson(upgradeBeans));
        return ZhongkaiResult.ok();
    }

//     * @param pact_number 合同编号

    /**
     * 为设备绑定用户
     *
     * @param unit_uuid    设备uuid
     * @param user_name    用户姓名
     * @param user_phone   用户手机号
     * @param user_number  身份证号
     * @param sex          性别 1男 2女
     * @param longitude    经度
     * @param latitude     纬度
     * @param province     省
     * @param city         市
     * @param country      区
     * @param town         乡镇
     * @param address      详细地址
     * @param ope_user     操作人员姓名
     * @param ope_uuid     操作人员uuid
     * @param pact_num     合同编号
     * @param set_vol_uuid 大客户uuid 传0代表没有
     * @param set_alias    设备别名
     */
    @Override
    public ZhongkaiResult bound_user(String unit_uuid, String user_name, String user_phone, String user_number, String sex, String longitude, String latitude, String province, String city, String country, String town,
                                     String address, String ope_user, String ope_uuid, String pact_num, String set_vol_uuid, String set_alias) {
        if (StringUtils.isNullOrEmpty(unit_uuid) || StringUtils.isNullOrEmpty(user_name)
                || StringUtils.isNullOrEmpty(user_phone) || StringUtils.isNullOrEmpty(user_number)
                || StringUtils.isNullOrEmpty(longitude) || StringUtils.isNullOrEmpty(latitude)
                || StringUtils.isNullOrEmpty(province) || StringUtils.isNullOrEmpty(city)
                || StringUtils.isNullOrEmpty(country) || StringUtils.isNullOrEmpty(address) || StringUtils.isNullOrEmpty(pact_num)
                || StringUtils.isNullOrEmpty(set_vol_uuid) || StringUtils.isNullOrEmpty(set_alias)


                ) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + unit_uuid + "'"); //验证设备

        if (setUnit == null) {
            return ZhongkaiResult.build(500, "设备不存在");
        } else if ("2".equals(setUnit.getSetRemove())) {
            return ZhongkaiResult.build(500, "设备已被删除");
        } else if ("2".equals(setUnit.getSetBound())) {
            return ZhongkaiResult.build(500, "该设备已绑定过用户");
        }


        // setUnit.setApp
        AppUser appUser = (AppUser) iBaseDao.get("from AppUser au where au.appPhone='" + user_phone + "'"); //查询客户是否存在


        //验证地址
        Province province1 = (Province) iBaseDao.get("from Province pr where pr.provinceId='" + province + "'");

        City city1 = (City) iBaseDao.get("from City pr where pr.cityId='" + city + "'");

        Country country1 = (Country) iBaseDao.get("from Country pr where pr.countryId='" + country + "'");


        if (province1 == null || city1 == null || country1 == null) {
            return ZhongkaiResult.build(500, "该地区不存在,请重新选择");
        }
        String address_all = "";

        if ("1".equals(town) || StringUtils.isNullOrEmpty(town)) {
            address_all = province1.getName() + city1.getName() + country1.getName() + address;

        } else {
            Town town1 = (Town) iBaseDao.get("from Town pr where pr.townId='" + town + "'");
            if (town1 == null) {
                return ZhongkaiResult.build(500, "该地区不存在,请重新选择");
            }

            address_all = province1.getName() + city1.getName() + country1.getName() + town1.getName() + address;
        }

/*        if (town1 == null) {
            address_all = province1.getName() + city1.getName() + country1.getName() + address;

        } else {
            address_all = province1.getName() + city1.getName() + country1.getName() + town1.getName() + address;
        }*/


        if ("0".equals(set_vol_uuid)) {
            setUnit.setSetVolName("无");
            setUnit.setSetVolUuid("无");
        } else {
            Chinaset chinaset = (Chinaset) iBaseDao.get("from Chinaset se where se.uuid='" + set_vol_uuid + "'");
            if (chinaset == null) {
                return ZhongkaiResult.build(500, "该大客户不存在");
            } else {
                setUnit.setSetVolName(chinaset.getSetName());
                setUnit.setSetVolUuid(set_vol_uuid);
            }
        }

        String uuid;

        long millis = new DateTime().getMillis(); //获取当前系统时间戳


        if (appUser == null) {

            appUser = new AppUser();


            uuid = TTHelp.generate();
            appUser.setAppUuid(uuid);
            appUser.setAppName(user_name);
            appUser.setAppPhone(user_phone);
            appUser.setUserNumber(user_number); //身份证号

            appUser.setAppVice("户主用户");
            appUser.setAppViceId(3);

            //加密
            try {
                String pass = CryptoUtil.encode64(CryptoUtil.SALT, "123456");

                //设置加密后的密码
                appUser.setAppPassword(pass);
            } catch (Exception e) {
                e.printStackTrace();
                return ZhongkaiResult.build(400, "数据加密失败");
            }


            appUser.setAppAddress(address);
            appUser.setAppProvince(province);
            appUser.setAppCity(city);
            appUser.setAppCountry(country);


            appUser.setAppTime(millis);
            appUser.setAppRemove("1");
            appUser.setAppSex(sex);


            appUser.setAddress_all(address_all);

            appUser.setAppImg("http://111.61.64.62:8001/group1/M00/00/01/wKgZhV3krh2AaPVDAAQqKpbszHg957.jpg");

            iBaseDao.save(appUser);
        } else {

            uuid = appUser.getAppUuid();
            appUser.setAppName(user_name); //更新姓名
            appUser.setUserNumber(user_number); //身份证号

            appUser.setAppVice("户主用户"); //用户权限
            appUser.setAppViceId(3);


            // appUser.setAppAddress(address);
            // appUser.setAppProvince(province);
            // appUser.setAppCity(city);
            //appUser.setAppCountry(country);

/*            if (!StringUtils.isNullOrEmpty(town)) {
                appUser.setAppTown(town);
            }*/


            appUser.setAppMoTime(millis); //时间
            appUser.setAppRemove("1"); //非删除状态
            appUser.setAppSex(sex); //性别


            //appUser.setAddress_all(address_all);


            iBaseDao.update(appUser);
        }
//...................................................................
        AppRole appRole = (AppRole) iBaseDao.get("from AppRole su where su.roleName='户主用户'");

        if (appRole == null) {
            return ZhongkaiResult.build(500, "户主权限缺失,请联系管理员");
        }
        FsonUser fsonUser = new FsonUser();//父子关系表
        fsonUser.setfUid(setUnit.getSetUuid()); //可操控设备的uuid
        fsonUser.setAppPhone(user_phone); //用户手机号
        fsonUser.setFatherPhone("0");//父用户手机号如果是户主用户存入0
        fsonUser.setAppRole(appRole.getId());//角色id
        fsonUser.setAppUuid(uuid);//可操控设备用户的唯一标识
        fsonUser.setfUuid("0");//父用户的唯一标识户主存入0
        fsonUser.setSetAlias(set_alias);//设备别名
        iBaseDao.save(fsonUser);
//...................................................................

        setUnit.setUserUuid(uuid);
        setUnit.setUserPhone(user_phone);
        setUnit.setUserName(user_name);
        setUnit.setSetBound("2");

        setUnit.setLongitude(longitude);
        setUnit.setLatitude(latitude);

        setUnit.setAppAddress(address);
        setUnit.setAppProvince(province);
        setUnit.setAppCity(city);
        setUnit.setAppCountry(country);

        setUnit.setSetBindTime(millis);

        if (!StringUtils.isNullOrEmpty(town)) {
            setUnit.setAppTown(town);
        }


        setUnit.setAppAddressAll(address_all);

        setUnit.setOpeUuid(ope_uuid); //录入人员uuid
        setUnit.setOpeUser(ope_user); //录入人员昵称

        setUnit.setPactNumber(pact_num);//合同编号
        //setUnit.setPactNumber(pact_number);

        setUnit.setSetAlias(set_alias); //设备别名

        iBaseDao.update(setUnit);

        return ZhongkaiResult.ok();
    }


    /**
     * 服务器默认版本号查询
     */
    @Override
    public ZhongkaiResult versions_code() {

        SystemVersions systemVersions = (SystemVersions) iBaseDao.get("from SystemVersions sp where sp.is_default=1"); //数据空 取出数据库中默认的系统

        if (systemVersions == null) {
            return ZhongkaiResult.build(500, "服务器未设置默认版本");
        } else {
            return ZhongkaiResult.ok(systemVersions.getVersions());
        }


    }

    @Override
    public ZhongkaiResult getBigUserList() {
        SetRole setRole = (SetRole) iBaseDao.get("from SetRole sr where sr.name='大客户'");

        if (setRole == null) {

            return ZhongkaiResult.build(500, "大客户角色不存在");
        }
        //Chinaset"setRole", setRole.getId()
        //  Chinaset
        List list = iBaseDao.find("from Chinaset ca where ca.setRole=" + setRole.getId());
        return ZhongkaiResult.ok(list);
    }


    /**
     * 设备托管
     *
     * @param unit_uuid   设备uuid
     * @param trusteeship 托管参数 1取消托管  2托管
     */
    @Override
    public ZhongkaiResult uniTrusteeship(String unit_uuid, String trusteeship) {

        if (StringUtils.isNullOrEmpty(unit_uuid)) {
            return ZhongkaiResult.build(500, "参数不完整");
        }

        if (StringUtils.isNullOrEmpty(trusteeship)) {

            Object o = iBaseDao.get("select trusteeship from SetUnit su where su.setUuid='" + unit_uuid + "'");//验证设备

            if (o == null) {
                return ZhongkaiResult.build(500, "设备不存在");
            }

            return ZhongkaiResult.ok(o);
        }


        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + unit_uuid + "'");

        if (setUnit == null) {
            return ZhongkaiResult.build(500, "设备不存在");
        } else if ("2".equals(setUnit.getSetRemove())) {
            return ZhongkaiResult.build(500, "设备已被删除");
        } else if ("1".equals(setUnit.getSetBound())) {
            return ZhongkaiResult.build(500, "该设备未绑定用户");
        } else if (trusteeship.equals(setUnit.getTrusteeship())) {
            if ("1".equals(trusteeship)) {
                return ZhongkaiResult.build(500, "您的设备已经取消托管");

            } else {
                return ZhongkaiResult.build(500, "您的设备已经托管");
            }
        }


        setUnit.setTrusteeship(trusteeship);

        iBaseDao.save(setUnit);
        return ZhongkaiResult.ok();
    }


    /***
     * 解除绑定
     *
     * @param unit_uuid  设备uuid
     * @param user_uuid  用户uuid
     * */
    @Override
    public ZhongkaiResult relieveUnit(String unit_uuid, String user_uuid) {
        if (StringUtils.isNullOrEmpty(unit_uuid) || StringUtils.isNullOrEmpty(user_uuid)) {
            return ZhongkaiResult.build(500, "参数不完整");
        }


        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + unit_uuid + "'"); //获取设备


        if ("1".equals(setUnit.getSetBound())) {
            return ZhongkaiResult.build(500, "此设备未绑定用户");
        }


        if (!user_uuid.equals(setUnit.getUserUuid())) {

            return ZhongkaiResult.build(500, "用户与设备不匹配");
        }

        //   FsonUser  =
        List<FsonUser> list = iBaseDao.find("from FsonUser fs where fs.fUid='" + unit_uuid + "'");

        for (FsonUser fsonUser : list) {
            iBaseDao.delete(fsonUser);
        }

        setUnit.setSetBound("1");

        iBaseDao.update(setUnit);

        FsonUser fsonUser = (FsonUser) iBaseDao.get("from FsonUser fs where fs.appUuid='" + user_uuid + "' and fs.appRole=3");

        if (fsonUser != null) {
            return ZhongkaiResult.ok();
        }

        FsonUser fsonUser2 = (FsonUser) iBaseDao.get("from FsonUser fs where fs.appUuid='" + user_uuid + "' and fs.appRole=2");
        AppUser appUser = (AppUser) iBaseDao.get("from AppUser au where au.appUuid='" + user_uuid + "'"); //查询客户是否存在

        if (fsonUser2 != null) {

            if (appUser != null) {
                appUser.setAppViceId(2);
                appUser.setAppVice("子用户");

                iBaseDao.update(appUser);
                return ZhongkaiResult.ok();
            }
        } else {
            if (appUser != null) {
                appUser.setAppViceId(1);
                appUser.setAppVice("普通用户");

                iBaseDao.update(appUser);
                return ZhongkaiResult.ok();
            }
        }

        return ZhongkaiResult.ok();
    }


}
